//拦截请求头统一处理
const APIError=require("../until/until").APIError;
const jwt = require('jwt-simple') //引入jwt模块
module.exports = { 
	setToken:(obj)=>{
		 return jwt.encode(obj, 'mvc')  //返回加密结果   jwt.encode('加密的对象','加密的秘钥')
	},
	checkToken:()=>{
		//拦截除了登录以外的所有api接口
		return async(ctx,next)=>{
			let path=ctx.request.path;
			if (path.startsWith('/api/')){
				if(path.endsWith('/login')||path.endsWith('/register')){ 
					await next();
				}else{
					 let token = ctx.request.headers['token']   
					 // console.log("token11",token);
					 if(token&&token!='null'&&token!="undefined"){  
						var tk = jwt.decode(token,'mvc') 
						if(tk.id){ 
							 ctx.state.userInfo=Object.assign({},ctx.state.userInfo||{},tk) 
							 await next();
						 }else{
							 throw new APIError(401,"解析token失败"); 
						 } 
					 }else{
						 // console.log("token",token);
						throw new APIError(400,"没有权限访问，联系管理员");
					 }
				}
			}else{
				await next();
			}
		}
	},
	restify: (pathPrefix) => {
		//拦截所有api接口设置统一响应方法
		pathPrefix = pathPrefix || '/api/';
		return async (ctx, next) => {
			if (ctx.request.path.startsWith(pathPrefix)) { 
				ctx.send = (data) => {
					ctx.response.type = 'application/json'; 
					ctx.response.body =data.code?data:{
						code:200,
						data
					};
				}
				try {
					await next();
				} catch (e) { 
					ctx.response.status = 400;
					ctx.response.type = 'application/json';
					ctx.response.body = {
						code: e.code || 'internal:unknown_error',
						message: e.message || ''
					};
				}
			} else {
				await next();
			}
		};
	}
};
